import inspect
from pathlib import Path
import sys
import gi
gi.require_version("Gtk", "4.0")

# To make this available install Vte with:
#     sudo apt install libvte-2.91-gtk4-dev
gi.require_version('Vte', '3.91')

from gi.repository import GObject, GLib, Vte, Gtk  # noqa


def print_function_parameters(func):
    sig = inspect.signature(func)
    print(f"Function: {func.__name__}")
    print("Parameters:")
    for param in sig.parameters.values():
        print(f"  {param.name}: {param.annotation} = {param.default}")

GObject.type_register(Vte.Terminal)


class KuraTerm(Gtk.Application):

    def __init__(self):
        super().__init__(application_id='org.example.vte')

    def do_activate(self):
        self._builder = Gtk.Builder()
        self._builder.add_from_file(str(
            Path(__file__).parent / 'kuraterm.glade'
        ))

        # Get objects
        def go(identifier):
            widget = self._builder.get_object(identifier)
            if widget is None:
                raise ValueError('Widget "{}" not found'.format(identifier))
            return widget

        # Get widgets
        self._terminal: Vte.Terminal = go('terminal')
        self._window = go('window')
        self._window.set_application(self)

        self._window.connect('close-request', self.stop)
        self._terminal.connect('child-exited', self.on_child_exited_cb2)

        self.on_child_exited_cb2(self._terminal, 0)
        # Show app
        self._window.set_default_size(800, 480)
        self._window.present()

    def on_child_exited_cb(self, term, status, user_data=None):
        self._terminal.spawn_sync(
            Vte.PtyFlags.DEFAULT,
            None,
            ['/bin/bash'],
            None,
            GLib.SpawnFlags.DEFAULT,
        )

    def on_child_exited_cb2(self, term, status, user_data=None):
        self._terminal.spawn_async(
            Vte.PtyFlags.DEFAULT,
            None,
            ['/bin/bash'],
            None,
            GLib.SpawnFlags.DEFAULT,
            None,
            None,
            -1,
            None,
            None
        )

    """
    void vte_pty_spawn_with_fds_async(
                                    VtePty*, 
                                    const char*, 
                                    const char* const*, 
                                    const char* const*, 
                                    const int*, 
                                    int, 
                                    const int*, 
                                    int, 
                                    GSpawnFlags, 
                                    GSpawnChildSetupFunc, 
                                    gpointer, 
                                    GDestroyNotify, 
                                    int, 
                                    GCancellable*, 
                                    GAsyncReadyCallback, 
                                    gpointer
    )
    """

    def on_child_exited_cb3(self, term, status, user_data=None):
        pty = Vte.Pty.new_sync(Vte.PtyFlags.DEFAULT)
        self._terminal.set_pty(pty)

        pty.spawn_async(
            None,
            ["/bin/python"],
            None,
            GLib.SpawnFlags.DO_NOT_REAP_CHILD,
            None,
            None,
            -1,
            None,
            self.ready
        )

    def ready(self, pty, task, param):
        print('type pty: ', type(pty))
        print('type task: ', type(task))
        print('type param: ', type(param))

    def send_command(self, command):
        self._terminal.feed_child(command + '\n', len(command) + 1)

    def stop(self, widget):
        self.quit()  # Use application's own quit method for Gtk4
        return True  # 需要返回布尔值来控制关闭行为

if __name__ == '__main__':
    try:
        # help(KuraTerm.on_child_exited_cb3)
        # print_function_parameters(Vte.Terminal.spawn_async)
        app = KuraTerm()
        app.run(sys.argv)

    except KeyboardInterrupt:
        pass
